<template>
	<view class="tab">
		<scroll-view class="tab-scroll" scroll-x  ref="scroll">
			<view class="tab-scroll__box" ref="tabRef">
				<view 
					v-for="(item,index) in data" 
					class="tab-scroll__item" 
					:class="{active: activeIndex === index}"
					:key="index"
					@click="clickTab(item,index)">{{item.name}}
				</view>
			</view>
		</scroll-view>
		<view class="tab-icons" @click="link">
			<uni-icons type="gear" size="26" color="#666"></uni-icons>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 当前下标
				activeIndex: 0
			}
		},
		methods: {
			// tab_item点击事件
			clickTab(item,index) {
				this.activeIndex = index
				this.$emit('tab', {
					data: item,
					index: index
				})
			},
			// 进入标签管理
			link() {
				uni.navigateTo({
					url: '/pages/home-label/home-label'
				})
			}
		},
		props: {
			data: {
				type: Array,
				default() {
					return []
				}
			},
			tabIndex: {
				type: Number,
				default: 0
			}
		},
		watch: {
			tabIndex(newIndex) {
				this.activeIndex = newIndex
			},
			activeIndex() {
				
				// #ifdef H5
					const target = this.$refs.tabRef.$children[this.activeIndex].$el,
								offsetLeft = target.offsetLeft,
								scrollEl  = this.$refs.scroll.$children[0].$el.parentNode.parentNode
								
					scrollEl.scrollTo(offsetLeft, 0)
								
				// #endif
							
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tab{
		width: 100%;
		border-bottom: 1px solid #f5f5f5;
		background-color: #fff;
		box-sizing: border-box;
		display: flex;
		.tab-scroll{
			flex: 1;
			overflow: hidden;
			.tab-scroll__box{
				display: flex;
				height: 90upx;
				align-items: center;
				flex-wrap: nowrap;
				.tab-scroll__item{
					// 不让元素挤压在一推
					flex-shrink: 0;
					padding: 0 20upx;
					color: #333;
					font-size: 28upx;
					&.active{
						color: $mk-base-color;
					}
				}
			}
		}
		.tab-icons{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 90upx;
			flex: 0 0 90upx;
			position: relative;
			&::after {
				position: absolute;
				content: '';
				width: 1px;
				background: #eee;
				left: 0;
				top: 24upx;
				bottom: 24upx;
			}
		}
	}
</style>
